{% extends 'web/layout/manage.html' %}
{% load static %}
{% block title %}File{% endblock title %}
{% block css %}
<style>

    .panel-default{
        margin-top:10px;
    }
    .panel-default .panel-heading {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
        }
    .panel-body{
        padding:0px;
    }
    .title_list{
        border-right:1px solid #dddddd;
        min-height: 500px;
    }
    .content{
        border-left:1px solid #dddddd;
        min-height: 600px;
        margin-left: -1px;
    }
    .editormd-fullscreen{
            z-index: 1001;
        }
    .panel-default > .panel-heading .function .upload {
            overflow: hidden;
        }

    .panel-default > .panel-heading .function .upload input {
        opacity: 0;
        position: absolute;
        top: 0;
        bottom: 0;
        width: 76px;
        left: -2px;
        overflow: hidden;
    }

    .upload-progress {
        position: fixed;
        right: 2px;
        bottom: 2px;
        width: 400px;
    }

    .upload-progress .progress-error {
        color: red;
    }

</style>
{% endblock css %}
{% block content %}

<!-- panel -->
<div class="container-fluid bs-example" data-example-id="table-within-panel">    <!-- container-fluid -->
    <div class="panel panel-default">
        <div class="panel-heading">
            <div>
                <i class="fa fa-book" aria-hidden="true"></i> 
                <a href="{% url 'web:files' project_id=request.tracer.project.id %}">文件库<a>
                {% for row in folder_list %}
                    | <a href="{% url 'web:files' project_id=request.tracer.project.id %}?folder_id={{row.id}}">{{row.name}}<a>
                {% endfor %}
            </div>        
            <div>
                
                <!-- Modal Button-->
                <div class="function">
                    <div class="btn btn-primary btn-xs upload" style="position: relative">
                        <div><i class="fa fa-upload" aria-hidden="true"></i> 上传文件</div>
                        <input type="file" multiple name="uploadFile" id="uploadFile">
                    </div>
                    <a class="btn btn-success btn-xs" data-toggle="modal" data-target="#addModal" data-whatever="新建文件夹">
                        <i class="fa fa-plus-circle" aria-hidden="true"></i> 新建文件夹
                    </a>
                </div>



                <!-- Modal -->
                <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="myModalLabel">新建文件夹</h4>
                        </div>
                        <div class="modal-body">
                        
                            <form id="FileForm">
                                {% csrf_token %}
                                <input class="hide" type="text" name="fid" id="fid">
                                {% for field  in folder_obj %}
                                    <div class="form-group">
                                        <label for="{{ field.id_for_label}}">{{field.label}}</label>
                                        {{field}}
                                        <span class="error-msg"></span>    
                                    </div>
                                {% endfor %}
                            
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default btn-xs" data-dismiss="modal">关 闭</button>
                            <button id="btnSubmit" type="button" class="btn btn-primary btn-xs">提 交</button>
                        </div>
                        </div>
                    </div>
                </div>
                <!-- Modal End -->

              <!--   <a type="button" class="btn btn-success btn-xs" href={% url 'web:files' project_id=request.tracer.project.id %}>创建文件夹</a> -->
            </div>
            
        </div>
            <table class="table">
                <thead>
                    <tr>
                        <th>名称</th>
                        <th>文件大小</th>
                        <th>更新者</th>
                        <th>更新时间</th>
                        <th></th>  <!-- for 编辑|删除 -->
                    </tr>
                </thead>
                <tbody id = "fileDisplayList">
                    {% for row in forms %}
                        <tr>
                            <td>
                                {% if row.file_type == 2 %}
                                    <a href="{% url 'web:files' project_id=request.tracer.project.id %}?folder_id={{row.id}}">{{ row.name}}</a>
                                {% else %}
                                    <!-- 
                                    <a href="{% url 'web:file_download' project_id=request.tracer.project.id %}?folder_id={{row.id}}">{{ row.name}}</a>
                                    -->
                                    <a class="fileDownload" data-key="{{row.key}}">{{ row.name}}</a>

                                {% endif %}
                            
                            </td>
                            <td>
                                {% if row.file_size %}
                                    {{ row.file_size}}
                                {% endif %}
                            </td>
                            <td>{{ row.update_user.username}}</td>
                            <td>{{ row.update_datetime}}</td>
                            <td class="modal-title">
                                {% if row.file_type == 2 %}
                                    <a data-toggle="modal" data-target="#addModal" data-whatever="编辑文件夹" data-fid="{{row.id}}" data-name="{{row.name}}">
                                        编辑
                                    </a>
                                {% else %}
                                    <!-- 
                                    <a class="fileDownload" href="{% url 'web:file_download' project_id=request.tracer.project.id %}?folder_id={{row.id}}">
                                    -->
                                    <a class="fileDownload" data-key="{{row.key}}" >
                                       下载 
                                    </a>
                                {% endif %}
                                |
                                <a data-toggle="modal" data-target="#deleteModal" data-fid="{{row.id}}">删除</a>
                            </td>
                        </tr>
                    {% endfor %}



                </tbody>
            </table>
    </div>
<div>
<!-- Modal delete -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">

            <div class="alert alert-danger alert-dismissible fade in" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
                
                <h4>是否要确定删除？</h4>
                <p style="padding-top: 20px;padding-bottom: 20px;">
                    文件夹中包含的所有的文件都会被删除。
                </p>

                <p style="text-align:right">
                    <button type="button" class="btn btn-default btn-sm" data-dismiss="modal">取消</button>
                    <button id="btnDelSubmit" type="button" class="btn btn-danger btn-sm">确认</button>
                </p>
            </div>

    </div>
</div>
<!-- Modal delete End -->

<!--利用panel生成进度条，样式使用-连接, 默认load时隐藏-->
    <div id="uploadProgress" class="upload-progress hide">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <i class="fa fa-cloud-upload" aria-hidden="true"></i> 上传进度
            </div>
            <!--放置进度条table的地方-->
            <table class="table">
                <tbody id="progressList">

                </tbody>
            </table>
        </div>
    </div>

    
<!--进度条模板(隐藏，仅供复制使用)，每一个文件赋值一份模板进panel-->
    <div class="hide">
        <table id="progressTemplate">
            <tr>
                <td>
			 <!-- 用于显示文件名称-->
                    <div class="name"></div>
			 <!-- 从bootstrap拿来的进度条 -->
                    <div class="progress">
                        <div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar"
                             aria-valuenow="0"
                             aria-valuemin="0"
				             aria-valuemax="100" style="width: 0%;">
                            0%
                        </div>
                    </div>
			 <!--显示error的地方 -->
                    <div class="progress-error"></div>
                </td>
            </tr>
        </table>
    </div>

<!--显示文件模板(隐藏，仅供复制使用)，每一个文件赋值一份模板进panel-->
    <div class="hide">
        <table id="displayFilesTemplate">
        <!-- 用于显示文件名称-->
            <tbody>
                <tr>
                    <td ><a class="name"><a></td>
                    <td class="file_size"></td>
                    <td class="update_user"></td>
                    <td class="update_datetime"></td>
                    <td>
                        <a class='downloadFile' >
                        下载 
                        </a>
                        |
                        <a class="delFile" data-toggle="modal" data-target="#deleteModal" data-fid="{{row.id}}">删除</a> 
                    </td>
                </tr>
            </tbody>
        </table>
    </div>



{% endblock content %}
{% block js %}
<script src="{% static 'js/cos-js-sdk-v5.min.js' %} "> </script>   



<script>
    var URL_PATH_FILE_BASE = "{% url 'web:files' project_id=request.tracer.project.id %}"; //to any url
    var URL_DELETE_FOLDER = "{% url 'web:files_delete' project_id=request.tracer.project.id %}"; //to any url
    var URL_UPLOAD_FILE = "{% url 'web:files_upload' project_id=request.tracer.project.id %}"; //to any url
    var URL_COS_CREDENTIAL = "{% url 'web:cos_credential' project_id=request.tracer.project.id %}?bucket={{request.tracer.project.bucket}}&region={{request.tracer.project.region}}"; //to any url

    var cos;
    $(function(){
            initCOS();
            initAddModal();
            bindClickBtnSubmit();
            bindClickBtnDelSubmit();
            bindChangeUploadFile();
            bindClickDownloadFile();
        });

    function initAddModal() {
        $('#addModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget); // Button that triggered the modal
            var recipient = button.data('whatever'); // Extract info from data-* attributes
            var name = button.data('name');
            var fid = button.data('fid');
            //var name = button.data('name'); // Extract info from data-* attributes
            //var fid = button.data('fid'); // Extract info from data-* attributes
            var modal = $(this);
            //console.log('files.html, line 146: here')
            modal.find('.modal-title').text(recipient);
            //清除上一次编辑的信息
            //modal.find('.error-msg').empty();
            //modal.find('#id_name').val('');
            //document.getElementById('FileForm').reset();
            //$('#FileForm')[0].reset();

            if (fid){
                //编辑
                modal.find('.error-msg').empty();
                modal.find('#id_name').val(name); //把编辑中绑定的name放到form的input框传给后台/
                modal.find('#fid').val(fid);    //把编辑中绑定的fid放到隐藏的input框传给后台/
            }
            else{
                //新建
                modal.find('.error-msg').empty();
                //modal.find('#id_name').val('');
                //document.getElementById('FileForm').reset();
                $('#FileForm')[0].reset();

            }
        });

        $('#deleteModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget); // delete Button that triggered the modal
            var fid = button.data('fid');
            $('#btnDelSubmit').attr('fid',fid); //把编辑中绑定的name放到form的input框传给后台/
        });

    }


    function bindClickBtnSubmit(){
        $('#btnSubmit').click(function(){
            $('.error-msg').empty();
            //console.log('hi');
            $.ajax({
                url:location.href,  //自动获取浏览器的url
                type:'POST', //'POST', page?val=xxx&?val2=bbb
                dataType:'JSON',
                data: $('#FileForm').serialize(),
                success:function(ret){
                    //console.log(ret);
                    if (ret.status){
                        //$("#id_randCode").next().text(res.error);
                       location.href = location.href;

                    }else{
                        //console.log(ret.msg);
                        $.each(ret.msg,function(key,value){
                            $("#id_"+key).next().text(value[0]);
                        })
                    }
                }
            })
        })
    }


    function bindClickBtnDelSubmit(){
        $('#btnDelSubmit').click(function(){
            //$('.error-msg').empty();
            var fid = $(this).attr('fid');
            //console.log(fid);
            $.ajax({
                url:URL_DELETE_FOLDER, //to any url
                type:'GET', //'POST', page?val=xxx&?val2=bbb
                data:{'fid':fid},
                dataType:'JSON',
                success:function(ret){
                    //console.log(ret);
                    if (ret.status){
                        location.href = location.href;
                    }else{
                        
                       }
                }
            })
        })
    }
    
    function initCOS() {
        var URL_COS_CREDENTIAL = "{% url 'web:cos_credential' project_id=request.tracer.project.id %}?bucket={{request.tracer.project.bucket}}&region={{request.tracer.project.region}}"; //to any url
        cos = new COS({
//之前直接是secure id和key，现在是运行回调函数，这个回调函数发送get请求到credential
            getAuthorization: function (options, callback) {
                // 向django后台发送请求，获取临时凭证
//等效$.ajax({type:’GET’})
                $.get(URL_COS_CREDENTIAL, {
                //$.get("{% url 'web:cos_credential' project_id=request.tracer.project.id %}", {
                    // 可从 options 取需要的参数
                }, function (data) {
//data是从视图函数拿到的凭证返回值 
                        var credentials = data && data.credentials;
                        if (!data || !credentials) return console.error('credentials invalid');
                        callback({
                            TmpSecretId: credentials.tmpSecretId,
                            TmpSecretKey: credentials.tmpSecretKey,
                            XCosSecurityToken: credentials.sessionToken,
                            StartTime: data.startTime,
                            ExpiredTime: data.expiredTime,
                        });
                    });
                }
            });
        }






    function bindClickDownloadFile(){
        $('.fileDownload').click(ClickDownloadFile)
    }

    function ClickDownloadFile(){
        //console.log('bindclickDownloadFile run ok');
        var key = $(this).attr('data-key');
            
        cos.getObjectUrl({
        Bucket: '{{request.tracer.project.bucket}}', /* 必须 */
        Region: '{{request.tracer.project.region}}',     /* 存储桶所在地域，必须字段 */
        Key: key,              /* 必须 */
        Sign: true
        }, function(err, data) {
            //console.log(err || data.Body);
            if (err) return console.log(err);
            var downloadUrl = data.Url + (data.Url.indexOf('?') > -1 ? '&' : '?') + 'response-content-disposition=attachment'; // 补充强制下载的参数
            window.open(downloadUrl); // 这里是新窗口打开 url，如果需要在当前窗口打开，可以使用隐藏的 iframe 下载，或使用 a 标签 download 属性协助下载

        });
    }

    function bindChangeUploadFile() {
            $("#uploadFile").change(function () {
                $('#progressList').empty();
                // 获取要上传的所有文件对象列表
                var fileObjs = $(this)[0].files;
                var checkFilelist = [];
                $.each(fileObjs, function(index, fileObject){
                    checkFilelist.push({'name':fileObject.name, 'size':fileObject.size})
                });
                //发送ajax，确认size是否超出允许值
                $.post(
                    "{% url 'web:files_sizeauth' project_id=request.tracer.project.id %}",
                    JSON.stringify(checkFilelist),
                    function (ret){
                        if (ret.status){

                        }else{
                            alert(ret.msg);
                            location.href = location.href
                        }
                    }
                );
                //打开进度条
                $('#uploadProgress').removeClass('hide');	//根据id删除class

                //开始cos上传
                $.each(fileObjs, function (index, fileObject) {
                    var fileName = fileObject.name;
                    var fileSize = fileObject.size;
                    var key = (new Date()).getTime() + "_" + fileName;
                    //进度条标签复制和添加
                    var tr = $('#progressTemplate').find('tr').clone();  //复制hide的标签
                    tr.find('.name').text(fileName);		//增加名字
                    $('#progressList').append(tr);

                    
                    // 上传文件
                    cos.putObject({
                        Bucket: '{{request.tracer.project.bucket}}', /* 必须 */
                        Region: '{{request.tracer.project.region}}',     /* 存储桶所在地域，必须字段 */
                        Key: key,              /* 必须 */
                        StorageClass: 'STANDARD',
                        Body: fileObject, // 上传文件对象
                        onProgress: function (progressData) {
                            console.log("文件上传进度--->", fileName, JSON.stringify(progressData));
                            var percent = progressData.percent * 100 + '%';
                            tr.find('.progress-bar').text(percent);		//增加名字
                            tr.find('.progress-bar').css('width',percent);		//增加名字


                        }
                    }, function (err, ret_data) {
                        //console.log(err || ret_data);
                        if (ret_data.statusCode === 200) {
                            var csrf = $('input[name="csrfmiddlewaretoken"]').val();
                            var etag = ret_data.ETag;
                            var filePath = ret_data.Location;
                            $.ajax({
                                url:"{% url 'web:files_upload' project_id=request.tracer.project.id %}", //to any url
                                //url: '/csrf1.html',
                                type: 'POST',
                                headers:{'X-CSRFToken': csrf},
                                data: { 
                                    key:key,
                                    file_size:fileSize,
                                    etag:etag,
                                    file_path:filePath,
                                    {% if folder_id %}
                                        parent:{{folder_id}},
                                    {% endif %}
                                    name:fileName
                                    },
                                dataType: 'JSON',
                                success:function(ret){
                                    //console.log(ret);
                                    if (ret.status){
                                        var fileDisplayTr = $('#displayFilesTemplate').find('tr').clone();  //复制hide的标签
                                        var URL_FILE_DOWNLOAD = "{% url 'web:file_download' project_id=request.tracer.project.id %}?folder_id="+ret.msg.id
                                        
                                        // try ajax to download file for new created tag, but failed.
                                        //fileDisplayTr.find('.downloadFile').attr('onclick',"ClickDownloadFile();");		//增加
                                        //fileDisplayTr.find('.name').attr('onclick', "ClickDownloadFile();");		//ajax download
                                        /* ajax download at front end*/
                                        //fileDisplayTr.find('.downloadFile').attr('data-key',ret.msg.key);		//增加
                                        //fileDisplayTr.find('.name').attr('data-key', ret.msg.key);		//ajax download
                                        //fileDisplayTr.find('.name').attr('id', 'id_'+ret.msg.id);		//ajax download

                                        fileDisplayTr.find('.name').text(ret.msg.name);		//增加名字
                                        fileDisplayTr.find('.file_size').text(ret.msg.file_size);		//增加
                                        fileDisplayTr.find('.update_user').text(ret.msg.update_user);		//增加
                                        fileDisplayTr.find('.update_datetime').text(ret.msg.update_datetime);		//增加
                                        fileDisplayTr.find('.delFile').attr('data-fid',ret.msg.id);		//增加
                                        
                                        //django download
                                        fileDisplayTr.find('.downloadFile').attr('href',URL_FILE_DOWNLOAD);		//增加
                                        fileDisplayTr.find('.name').attr('href',URL_FILE_DOWNLOAD);		//增加
                                        
                                        $('#fileDisplayList').append(fileDisplayTr);
                                        
                                        //remove progress bar
                                        tr.remove();
                                    }
                                    else{
                                        tr.find('.progress-error').text(ret.msg);                                    
                                    }

                                }
                            });
                        }
                        else{
                            tr.find('.progress-error').text('前端消息：上传失败');
                            
                        }
                    });
                })
            })
        }


</script>

{% endblock js %}